'use strict';

const path = require('path');
const Package = require('@caiheping-cli-dev/package');
const log = require('@caiheping-cli-dev/log');
const { spawn } = require('@caiheping-cli-dev/utils');

const SETTINGS = {
    init: '@caiheping-cli-dev/init',
}
const CACHE_DIR = 'dependencies';

async function exec() {
    let pkg;
    let targetPath = process.env.CLI_TARGET_PATH;
    let storeDir = '';
    const homePath = process.env.CLI_HOME_PATH;
    log.verbose(process.env.CLI_TARGET_PATH);
    log.verbose(process.env.CLI_HOME_PATH);
    const cmdObj = arguments[arguments.length - 1];
    // console.log(cmdObj.name(), 123);
    const packageName = SETTINGS[cmdObj.name()]; // cmdObj.name() => init
    const packageVersion = 'latest';
    if (!targetPath) {
        // 生成缓存路径
        targetPath = path.resolve(homePath, CACHE_DIR);
        storeDir = path.resolve(targetPath, 'node_modules');
        // console.log(targetPath, storeDir);
        pkg = new Package({
            targetPath,
            storeDir,
            packageName,
            packageVersion
        });
        if (await pkg.exists()) {
            // 更新package
            console.log('更新package');
            await pkg.update();
        } else {
            // 安装package
            console.log('安装package');
            await pkg.install();
        }
    } else {
        pkg = new Package({
            targetPath,
            packageName,
            packageVersion
        });
    }
    const rootFile = pkg.getRootFilePath();
    /**
     * caiheping-cli-dev init test -d -tp /d/jiagou/cli/caiheping-cli-dev/commands/init
     * -tp 执行的目标文件，没有的话就npm拉取的
     */
    if (rootFile) {
        // console.log(rootFile, 88888);
        try {
            // require(rootFile).call(null, Array.from(arguments));

            // 通过node多进程方式加载文件
            const args = Array.from(arguments);
            // console.log(args, 5555);
            const cmd= args[args.length - 1];
            const o = Object.create(null);
            Object.keys(cmd).forEach(key => {
                if (cmd.hasOwnProperty(key) && !key.startsWith('_') && key !== 'parent') {
                    o[key] = cmd[key];
                }
            })
            args[args.length - 1] = o;
            const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`;
            const child = spawn('node', ['-e', code], {
                cwd: process.cwd(),
                stdio: 'inherit'
            })
            child.on('error', e => {
                log.error(e.message);
                process.exit(1);
            })
            child.on('exit', e => {
                log.verbose('命令执行成功', e);
                process.exit(e);
            })
        } catch (err) {
            log.error(err.message);
        }
        
    }
}


module.exports = exec;
